import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
// 导入的时候加{}，导出的时候会报错
import {
  Card,
  Alert,
  Typography,
  Button,
  Descriptions,
  Avatar,
  Modal,
  Form,
  Input,
  Select,
} from 'antd';
import ResourceCard from '@/components/ResourceCard';
import { currentUser, updateInfo } from '@/services/ant-design-pro/user';
import TagList from '@/components/TagList';
import { EditOutlined } from '@ant-design/icons';
import { getTags } from '@/services/ant-design-pro/links';
// import UploadPic from '@/components/UploadPic';
import axios from 'axios';

const { Option } = Select;

const tags = [];

const UserInfo = () => {
  const [form] = Form.useForm();
  const [userInfo, setUserInfo] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  const [nikename, setNikename] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [briefIntr, setBriefIntr] = useState('');
  const [hobbys, setHobbys] = useState('');
  const [avator, setAvator] = useState('');

  useEffect(() => {
    if (loading === false) {
      getUserInfo();
      getAllTags();
      setLoading(true);
    }
  });

  // 获取个人信息
  const getUserInfo = async () => {
    try {
      const res = await currentUser();
      setUserInfo(res.data);
      setEmail(res.data.email);
      setNikename(res.data.nikename);
      setPhone(res.data.phone);
      setBriefIntr(res.data.briefIntr);
      setAvator(res.data.avatar);
      setHobbys(Array.from(res.data.hobbys, ({ id }) => id + ''));
    } catch (error) {
      console.log(error);
    }
  };

  // const showModal = () => {
  //   setIsModalVisible(true);
  // };
  // const test = () => {
  //   console.log('123123');
  // };

  // 关闭修改框
  const handleOk = () => {
    setIsModalVisible(false);
    getUserInfo();
  };

  // 关闭修改框
  const handleCancel = () => {
    setIsModalVisible(false);
    getUserInfo();
  };

  // 提交个人信息修改
  const submitUserInfo = () => {
    const tempInfo = {
      email: email,
      phone: phone,
      nikename: nikename,
      briefIntr: briefIntr,
      hobbys: hobbys,
      avatar: avator,
    };
    update(tempInfo);
    setIsModalVisible(false);
    getUserInfo();
  };

  // 调用更新个人信息的接口
  const update = async (values) => {
    try {
      const res = await updateInfo({ ...values });
      console.log(res);
      // console.log(res.data.id);
    } catch (error) {
      console.log(error);
    }
  };

  // 获得所有标签
  const getAllTags = async () => {
    try {
      const res = await getTags();
      const temp = res.data;
      for (let i = 0; i < temp.length; i++) {
        tags.push(<Option key={temp[i].id}>{temp[i].tip}</Option>);
      }
      // console.log(res);
    } catch (error) {
      console.log(error);
    }
  };

  function UploadPic() {
    const upload = async ({ target }) => {
      const files = new FormData();
      files.append('file', target.files[0]);
      console.log(target.files[0]);

      const { data } = await axios.post('/api/user/uploadAvator', files, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      // console.log(data.avatorUrl);
      setAvator(data.avatorUrl);
    };
    return (
      <>
        <div>
          <input type="file" onChange={upload} />
        </div>
      </>
    );
  }

  return (
    <div>
      <Modal
        title="编辑个人资料"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={[
          <Button key="submit" type="primary" onClick={submitUserInfo}>
            确认修改
          </Button>,
        ]}
      >
        <Form
          // {...formItemLayout}
          layout="horizontal"
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 14,
          }}
          form={form}
          initialValues={{
            layout: {
              labelCol: { span: 4 },
              wrapperCol: { span: 14 },
            },
          }}
          // onValuesChange={onFormLayoutChange}
        >
          <Form.Item label="用户姓名">
            <Input
              placeholder="大佬怎么称呼？"
              value={nikename}
              onChange={(e) => {
                setNikename(e.target.value);
              }}
            />
          </Form.Item>
          <Form.Item label="上传头像">
            <UploadPic></UploadPic>
          </Form.Item>
          <Form.Item label="电话">
            <Input
              placeholder="有消息可以第一时间通知你哦"
              value={phone}
              onChange={(e) => {
                setPhone(e.target.value);
              }}
            />
          </Form.Item>
          <Form.Item label="邮箱">
            <Input
              placeholder="有消息可以第一时间用邮件通知你哦"
              value={email}
              onChange={(e) => {
                setEmail(e.target.value);
              }}
            />
          </Form.Item>
          <Form.Item label="个人简介">
            <Input
              placeholder="介绍一下自己吧"
              value={briefIntr}
              onChange={(e) => {
                setBriefIntr(e.target.value);
              }}
            />
          </Form.Item>
          <Form.Item label="技术方向">
            <Select
              mode="multiple"
              allowClear
              style={{
                width: '100%',
              }}
              placeholder="选择你的技术方向吧"
              onChange={(e) => {
                console.log(e);
                setHobbys(e);
              }}
              value={hobbys}
            >
              {tags}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
      <Card
        title="用户信息"
        extra={
          <Button type="link" icon={<EditOutlined />} onClick={() => setIsModalVisible(true)}>
            编辑资料
          </Button>
        }
      >
        <Card>
          <Avatar size={128} src={'http://localhost:9999' + userInfo.avatar} />
        </Card>

        <Descriptions
          bordered
          column={{
            xl: 1,
            lg: 1,
            md: 1,
            sm: 1,
            xs: 1,
          }}
        >
          <Descriptions.Item label="用户账号">
            {<div style={{ width: '400px' }}>{userInfo.username}</div>}
          </Descriptions.Item>
          <Descriptions.Item label="用户姓名">
            {<div style={{ width: '400px' }}>{userInfo.nikename}</div>}
          </Descriptions.Item>
          <Descriptions.Item label="电话">
            {<div style={{ width: '400px' }}>{userInfo.phone}</div>}
          </Descriptions.Item>
          <Descriptions.Item label="邮箱">
            {<div style={{ width: '400px' }}>{userInfo.email}</div>}
          </Descriptions.Item>
          <Descriptions.Item label="个人简介">
            {<div style={{ width: '400px' }}>{userInfo.briefIntr}</div>}
          </Descriptions.Item>
          <Descriptions.Item label="技术方向">
            {
              <div style={{ width: '100px' }}>
                <TagList tips={userInfo.hobbys} style={{ margin: 0 }} />
              </div>
            }
          </Descriptions.Item>
        </Descriptions>
      </Card>
    </div>
  );
};

export default UserInfo;
